package com.example.harmtorch_demo.slice;

import com.example.harmtorch_demo.ResourceTable;
import com.example.harmtorch_demo.harmtorch.Tensor;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.Text;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.global.resource.NotExistException;
import ohos.global.resource.RawFileEntry;
import ohos.global.resource.Resource;
import ohos.global.resource.ResourceManager;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;

import java.io.IOException;

public class MainAbilitySlice extends AbilitySlice implements Component.ClickedListener {

    DataReader imageGetter;
    Classifier classifier;

    private HiLogLabel label = new HiLogLabel(ohos.hiviewdfx.HiLog.LOG_APP, 0x00201, "test");

    private static final String DATA_PATH = "entry/resources/rawfile/t10k-images-idx3-ubyte";

    int[] answer = new int[10];
    float[] prob = new float[10];

    int idx = 0;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        Button but1 = (Button)findComponentById(ResourceTable.Id_but1);
        but1.setClickedListener(this);

        classifier = new Classifier(this);
        classifier.init();

        RawFileEntry rawFileEntry = getResourceManager().getRawFileEntry(DATA_PATH);
        try {
            Resource resource = rawFileEntry.openRawFile();
            imageGetter = new DataReader(resource);
            Tensor[] inps = new Tensor[10];
            imageGetter.readMul(inps, 10);
            for(int i = 0; i < 10; ++i) {
                Tensor output = classifier.getResult(inps[i]);
                for(int j = 0; j < 10; ++j) {
                    boolean bigger = output._tensor[j] > prob[i];
                    answer[i] = bigger ? j : answer[i];
                    prob[i] = bigger ? output._tensor[j] : prob[i];
                }
            }
            setUI(idx++);
        } catch (Exception e) {
            //e.printStackTrace();
            System.exit(0);
        }
    }

    byte[] getPicByte(int index) {
        ResourceManager resourceManager = getResourceManager();
        Resource resource = null;
        byte[] bytes = null;
        try {
            resource = resourceManager.getResource(ResourceTable.Media_test_1);
            /* 解除这段注释，可以使代码更好地运行
            switch(index) {
                case 0: resource = resourceManager.getResource(ResourceTable.Media_test_0); break;
                case 1: resource = resourceManager.getResource(ResourceTable.Media_test_1); break;
                case 2: resource = resourceManager.getResource(ResourceTable.Media_test_2); break;
                case 3: resource = resourceManager.getResource(ResourceTable.Media_test_3); break;
                case 4: resource = resourceManager.getResource(ResourceTable.Media_test_4); break;
                case 5: resource = resourceManager.getResource(ResourceTable.Media_test_5); break;
                case 6: resource = resourceManager.getResource(ResourceTable.Media_test_6); break;
                case 7: resource = resourceManager.getResource(ResourceTable.Media_test_7); break;
                case 8: resource = resourceManager.getResource(ResourceTable.Media_test_8); break;
                case 9: resource = resourceManager.getResource(ResourceTable.Media_test_9); break;
            }
            */

            
            bytes = new byte[resource.available()];
            //将 Resource 文件数据读入数组中
            resource.read(bytes);
        } catch (IOException | NotExistException e) {
            HiLog.warn(label, e.toString());
        }
    }

    void setUI(int index) {
        TaskDispatcher uiTaskDispatcher = this.getContext().getUITaskDispatcher();
        uiTaskDispatcher.asyncDispatch(new Runnable() {
            @Override
            public void run() {
                Text text = (Text)findComponentById(ResourceTable.Id_text_helloworld);
                text.setText(((Integer)answer[index]).toString() + "(" + ((Float)prob[index]).toString() + ")");

                Image image = (Image)findComponentById(ResourceTable.Id_image);

                byte[] bytes = getPicByte(index);

                // 用于 ImageSource的 create(bytes,srcOpts)方法
                ImageSource.SourceOptions srcOpts = new ImageSource.SourceOptions();
                //设置图片原格式也可以用 null
                srcOpts.formatHint="image/jpg";

                ImageSource imageSource = ImageSource.create(bytes,srcOpts);

                //通过ImageSource创建 PixelMap文件
                PixelMap pixelMap = imageSource.createPixelmap(null);

                //为Image 设置 PixelMap，显示图片
                image.setPixelMap(pixelMap);
            }
        });
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public void onClick(Component component) {
        setUI(idx++);
        if (idx == 10) {
            idx = 0;
        }
    }

}



